# setup
#编译选项
COMPILE_OPTS = -c -mcpu=cortex-m3  -mthumb  -mlittle-endian  -W -Wall -g -Werror  -nostartfiles
#包含的文件目录
INCLUDE_DIRS += -ILibrariesST/inc  
INCLUDE_DIRS += -IFreeRTOS/include 
INCLUDE_DIRS += -I FreeRTOS/portable

OBJ_DIR=build


UserOBJ+= $(patsubst %.c,%.o,$(wildcard User/*.c))



CC = arm-none-eabi-gcc
CFLAGS = $(COMPILE_OPTS) $(INCLUDE_DIRS) -D STM32F10X_MD -D VECT_TAB_FLASH  -D USE_STDPERIPH_DRIVER

CXX = arm-none-eabi-g++
CXXFLAGS = $(COMPILE_OPTS) $(INCLUDE_DIRS)

AS = arm-none-eabi-gcc
ASFLAGS = $(COMPILE_OPTS) -c

LD = arm-none-eabi-gcc
LDFLAGS =  -T LibrariesST/links/stm32_flash.ld -Wl,-Map=$(OBJ_DIR)/output.map --specs=nosys.specs


SIZE =arm-none-eabi-size

OBJCP = arm-none-eabi-objcopy
OBJCPFLAGS_BIN = -O binary
OBJCPFLAGS_HEX = -O ihex
#link option
AR = arm-none-eabi-ar
ARFLAGS = cr

Target_Name = "app"
FREE_RTOS = "LibrariesST/libstm32.a"
ST_LIB = "FreeRTOS/FreeRTOS.a"

all:  $(Target_Name).hex $(Target_Name).bin


dir:
	-mkdir -p $(OBJ_DIR)

$(ST_LIB):
	@make  -C LibrariesST
	
$(FREE_RTOS):
	@make  -C FreeRTOS	


	
$(Target_Name).elf: $(UserOBJ) $(ST_LIB) $(FREE_RTOS)
	@echo "Building $@ ..."
	@$(LD) $(LDFLAGS) $(UserOBJ) $(ST_LIB) $(FREE_RTOS) --output $(OBJ_DIR)/$@
	@$(SIZE) -d -t $(OBJ_DIR)/$@
	@echo "Building $@ Success!"

$(Target_Name).hex : dir $(Target_Name).elf 
	@echo "Building $@ ..."
	@$(OBJCP) $(OBJCPFLAGS_HEX) $(OBJ_DIR)/$(Target_Name).elf $(OBJ_DIR)/$@
	@echo "Building $@ Success!"
$(Target_Name).bin : $(Target_Name).elf
	@echo "Building $@ ..."
	@$(OBJCP) $(OBJCPFLAGS_BIN) $(OBJ_DIR)/$(Target_Name).elf $(OBJ_DIR)/$@
	@printf "\nBinFileSize: 0x%x Bytes\n\n" $$(stat -c "%s" $(OBJ_DIR)/$@)
	@echo "Building $@ Success!"

%.o:%.S
	@echo CC: $<
	@$(CC) $(CFLAGS) -c $< -o $@
%.o:%.c
	@echo CC: $<
	@$(CC) $(CFLAGS) -c $< -o $@

.PHYON: clean dl bootloader cleanall

bootloader:
	@make -C Bootloader

clean:
	@echo "Clean Temp..."
	@-rm  -f $(UserOBJ) 
	@-rm  -rf $(OBJ_DIR)
	@echo "Clean Done ..."
	@make clean -C Bootloader
cleanlibs:
	@make clean -C FreeRTOS
	@make clean -C LibrariesST
cleanall: clean cleanlibs

dl:
	JLinkExe -If SWD -device STM32F103ZE -CommanderScript Jlink/stm32.jlink
dlbl:
	JLinkExe -If SWD -device STM32F103ZE -CommanderScript Jlink/stm32.bootloader.jlink